﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QuickTasks.ViewModels.Data;
using QuickTasks.ViewModels.Properties;
using LocalSettings;
using System.Xml.Linq;

using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone.Tasks;
using Microsoft.Phone;
using System.Windows.Navigation;
using QuickTasks.ViewModels.Tables;
using Microsoft.Advertising.Mobile.UI;


namespace QuickTasks.Views.BackGrounds
{
    public partial class BackGrounds : PhoneApplicationPage
    {
        #region Global

      
        PanoramaBg objPanoramaBg = new PanoramaBg();
        string ImageName = "";
        string Placeid = "";
        string type;
        static string pid;

        #endregion

        #region constructor

        public BackGrounds()
        {
            InitializeComponent();
           
        }

        #endregion

        #region PageLoad
       
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("back"))
            {
                type = NavigationContext.QueryString["back"];
                Loadbackground(type);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            if (this.NavigationContext.QueryString.ContainsKey("Placeid"))
            {
                pid = NavigationContext.QueryString["Placeid"];
            }
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (NavigationContext.QueryString.TryGetValue("Placeid", out Placeid))
                {
                    lbxLoadBackGroundImages.ItemsSource = objPanoramaBg.GetBackGroundImages();
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded event In BackGrounds.xaml page", ex);
            }
        }

        #endregion

        #region Events

        private void lbxLoadBackGroundImages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxLoadBackGroundImages.SelectedIndex == -1)
                    return;
                string imageName = (lbxLoadBackGroundImages.SelectedItem as PanoramaBgProp).ImageName;
                List<AddressProp> objAddaddress = new List<AddressProp>();
                QuickTasks.ViewModels.Data.Common.saveSettings("SelectedBackground", imageName);
                Loadbackground(imageName);
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in lbxLoadBackGroundImages_SelectionChanged event In BackGrounds.xaml page", ex);
            }
        }
        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                App.AcitivityImgSrc = null;
                PhotoChooserTask phtochoser = new PhotoChooserTask();
                phtochoser.Completed += new EventHandler<PhotoResult>(phtochoser_Completed);
                phtochoser.Show();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in ApplicationBarMenuItem_Click event In BackGrounds.xaml page", ex);
            }
        }
        private void phtochoser_Completed(object sender, PhotoResult e)
        {
            try
            {
                if (e.TaskResult == TaskResult.OK)
                {
                    App.ImageBytes = new byte[e.ChosenPhoto.Length];
                    e.ChosenPhoto.Read(App.ImageBytes, 0, App.ImageBytes.Length);
                    e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
                    var imageSource = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                    App.AcitivityImgSrc = imageSource;
                    Dispatcher.BeginInvoke(() =>
                    this.NavigationService.Navigate(new Uri("/Views/BackGrounds/PhotoChooser.xaml?id=" + pid, UriKind.Relative)));
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in phtochoser_Completed event In BackGrounds.xaml page", ex);
            }
        }
        private void Loadbackground(string imageName)
        {
            try
            {
                QuickTasks.ViewModels.Data.Common.saveSettings("SelectedBackground", imageName);
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    var ActToDel = from t in context.back
                                   where t.id.ToString() == pid
                                   select t;
                    string img = "";

                    foreach (var acte in ActToDel)
                    {
                        img = acte.id.ToString();
                    }
                    if (pid == img)
                    {
                        foreach (var acte in ActToDel)
                        {
                            acte.name = imageName;

                            IQueryable<ImgBackground> back = from b in context.back where b.id.ToString() == pid select b;
                            ImgBackground backg = back.FirstOrDefault();
                            {
                                backg.name = acte.name;
                            };
                            context.SubmitChanges();
                            break;
                        }
                    }
                    else
                    {
                        ImgBackground back = new ImgBackground()
                        {
                            id = Convert.ToInt32(pid),
                            name = imageName

                        };
                        context.back.InsertOnSubmit(back);
                        context.SubmitChanges();
                    }


                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in Loadbackground method In BackGrounds.xaml page", ex);
            }
        }
                

                
            

        #endregion
    }
}